package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 20:19
 * @注释
 */
public class DirectConsumer {
    private static final String EXCHANGE_NAME = "direct_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPort(5672);
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel=connection.createChannel();
        //指定交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        //创建队列并绑定到xiaoyu路由键
        String queueName1 = "xiaoyu_queue";
        channel.queueDeclare(queueName1, true, false, false, null);
        //将队列绑定到指定交换机上，并绑定路由键
        channel.queueBind(queueName1, EXCHANGE_NAME, "xiaoyu");

        //创建队列
        String queueName2 = "xiaopi_queue";
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueBind(queueName2, EXCHANGE_NAME, "xiaopi");
        System.out.println(" [*] Waiting for message");
        //创建一个DeliverCallback来处理xiaoyu消息队列中的消息
        DeliverCallback xiaoyuDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [xiaoyu] Received '"+delivery.getEnvelope().getRoutingKey()+"':"+message);
        };
        DeliverCallback xiaopiDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [xiaopi] Received '"+delivery.getEnvelope().getRoutingKey()+"':"+message);
        };
        //开始消费xiaoyu消息队列中的消息
        channel.basicConsume(queueName1,true,xiaoyuDeliverCallback,consumerTag -> { });
        //开始消费xiaopi消息队列中的数据
        channel.basicConsume(queueName2,true,xiaopiDeliverCallback,consumerTag -> { });
    }
}
